package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.DishFlavor;
import com.itheima.reggie.mapper.DishMapper;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {

    @Autowired
    private DishFlavorService dishFlavorService;

    /**
     * 保存菜品以及口味的代码两张表
     *
     * @param dishDto
     */
    @Transactional//开启事务
    @Override
    public void saveWithFlavor(DishDto dishDto) {
        //保存菜品的基本信息
        this.save(dishDto);
        //获取保存菜品id
        Long id = dishDto.getId();
        //获取菜品口味,遍历,为菜品口味对象属性dishid赋值;
        List<DishFlavor> flavors = dishDto.getFlavors();
        for (DishFlavor flavor : flavors) {
            flavor.setDishId(id);
            //批量保存菜品口味
            dishFlavorService.save(flavor);
        }
    }

    /**
     * 修改数据查询回显
     *
     * @param id
     * @return
     */
    @Override
    public DishDto getByIdWithFlavor(Long id) {
        //根据id查询菜品信息id
        Dish dish = this.getById(id);
        //创建dishDto对象
        DishDto dishDto = new DishDto();
        //将dish数据复制到dishDto对象中
        BeanUtils.copyProperties(dish, dishDto);
        //在dish_flavor中根据菜品id查询口味信息
        LambdaQueryWrapper<DishFlavor> lqw = new LambdaQueryWrapper<>();
        lqw.eq(DishFlavor::getDishId, dish.getId());
        List<DishFlavor> list = dishFlavorService.list(lqw);
        //将口味封装到dishDto对象上
        dishDto.setFlavors(list);
        //返回dishDto对象
        return dishDto;
    }

    /**
     * 修改菜品信息
     *
     * @param dishDto
     */
    @Override
    @Transactional//开启事务
    public void updateWithFlavor(DishDto dishDto) {
        //修改菜品信息数据
        this.updateById(dishDto);
        //更新口味
        LambdaQueryWrapper<DishFlavor> lqw = new LambdaQueryWrapper<>();
        //查找之前的口味
        lqw.eq(DishFlavor::getDishId,dishDto.getId());
        //删除口味
        dishFlavorService.remove(lqw);
        //添加新口味
        List<DishFlavor> flavors = dishDto.getFlavors();
        for (DishFlavor flavor : flavors) {
            flavor.setDishId(dishDto.getId());
        }
        //批量添加
        dishFlavorService.saveBatch(flavors);
    }
}
